import logging
from logging.handlers import TimedRotatingFileHandler


# 模块变量
module_name = "日志模块"
version = "1.0"


def get_logger(
    logger_name="app_logger",
    log_file="LD-WIN-TOOLS.log",
    level=logging.INFO,
    fmt="%(asctime)s - [%(levelname)s:%(lineno)d]: %(message)s",
):

    # 避免重复添加处理器
    logger = logging.getLogger(logger_name)
    if logger.handlers:
        return logger  # 已初始化过，直接返回

    logger.setLevel(level)

    # 控制台处理器（通常控制台默认支持 utf-8，可不指定编码）
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_formatter = logging.Formatter(fmt)
    console_handler.setFormatter(console_formatter)

    # 文件处理器（必须指定 encoding="utf-8"）
    file_handler = TimedRotatingFileHandler(
        log_file,
        when="D",
        interval=10,
        backupCount=3,
        encoding="utf-8",  # 核心：解决中文乱码
    )
    file_handler.setLevel(level)
    file_formatter = logging.Formatter(fmt)
    file_handler.setFormatter(file_formatter)

    logger.addHandler(console_handler)
    logger.addHandler(file_handler)

    return logger
